﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/8/4 14:55:44
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using JWT;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using static MyWebApp.Helper.JwtHelper;

namespace MyWebApp.Controllers
{
    /// <summary>
    /// JWT 
    /// </summary>
    [Route("api/Jwt")]
    public class JwtController : ControllerBase
    {

        /// <summary>
        /// 创建JwtToken
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [Route("getToken")]
        public ActionResult CreateToken(string username, string pwd)
        {
            TokenResult result = new TokenResult();
            result.token = "";
            result.success = false;

            if (username != "" && pwd != "")
            {
                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow();
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                var payload = new Dictionary<string, object>
                {
                    { "username",username },
                    { "pwd", pwd },
                    { "exp", secondsSinceEpoch + 60*30} //失效时间秒  此处设置30分钟
                };

                result.token = SetJwtEncode(payload);
                result.success = true;
                result.message = "生成token成功";
            }
            else
            {
                result.message = "生成token失败";
            }

            return Ok(result);
        }

    }
}
